<template>
    <div class="checkout-container">
        <div v-for="(item, index) in carts" :key="item.id" class="cart-item">
            <el-row :gutter="20">
                <el-col :sm="24" :md="4">
                    <el-image :src="item.picUrl" fit="contain" class="product-image"></el-image>
                </el-col>
                <el-col :sm="24" :md="10">
                    <div class="product-info">
                        <div class="product-name">{{ item.productName }}</div>
                        <div class="product-price">￥{{ item.salePrice }}</div>
                    </div>
                </el-col>
                <el-col :sm="24" :md="6">
                    <el-form-item label="购买数量" class="quantity-form-item">
                        <el-input-number v-model="orderVo.details[index].buyCount" :min="1" :max="100" 
                                        :step="1" @change="updateQuantity(index)"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :sm="24" :md="4">
                    <el-button type="danger" size="small" @click="removeItem(index)" class="remove-button">-</el-button>
                </el-col>
                <el-col :sm="24" :md="4" class="total-col">
                    <div class="item-total">小计: ￥{{ item.salePrice * orderVo.details[index].buyCount }}</div>
                </el-col>
            </el-row>
        </div>
        
        <el-divider class="divider"></el-divider>
        
        <div class="address-section">
            <el-row :gutter="20">
                <el-col :sm="24" :md="18">
                    <el-form-item label="收货地址" prop="address">
                        <el-input type="textarea" v-model="address" rows="3" 
                                  placeholder="请输入详细收货地址"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </div>
        
        <el-divider class="divider"></el-divider>
        
        <div class="summary-section">
            <el-row :gutter="20">
                <el-col :sm="24" :md="18">
                    <div class="total-price">
                        <span>总计: </span>
                        <span class="total-amount">￥{{ calculateTotal() }}</span>
                    </div>
                </el-col>
            </el-row>
        </div>
        
        <div class="action-buttons">
            <el-row :gutter="20">
                <el-col :sm="24" :md="18">
                    <el-button type="primary" @click="commit" class="submit-button" :loading="submitting">
                        提交订单
                    </el-button>
                    <el-button @click="goBack" class="back-button">返回</el-button>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ElFormItem, ElMessage, ElInputNumber } from "element-plus";
import { ref, reactive, onMounted, computed } from "vue"
import { useRoute, useRouter } from "vue-router";
import {store} from "@/common/store";

const route = useRoute()
const router = useRouter()
const carts = ref<any>([])
const address =ref()
axios.get("/shopcartapi/"+store.userinfo.id+"/address").then(res =>{
    address.value=res.data
})

const orderVo = reactive({
    id: store.userinfo.id,
    order: { custmerId: store.userinfo.id, targetAddr: "", totalCount: 0, status: 0 },
    details: <any>[]
})
console.log(address)
const submitting = ref(false)

function findCarts(custmerid: string) {
    let url = `/shopcartapi/${custmerid}/shopcarts`  
    axios.get(url).then(res => {
        carts.value = res.data.data
        orderVo.details = [];
        for (let i = 0; i < carts.value.length; i++) {
            let orderDetail = { productId: carts.value[i].productId, salePrice: carts.value[i].salePrice, buyCount: carts.value[i].buyCount };
            orderVo.details.push(orderDetail);
        }
    })
}

function removeItem(idx: number) {
    const custmerId = store.userinfo.id;
    const cartItemId = carts.value[idx].id;
    
    axios.delete(`/shopcartapi/${custmerId}/shopcarts/${cartItemId}`);
    orderVo.details.splice(idx, 1)
    carts.value.splice(idx, 1)
}

function updateQuantity(index: number) {
    // 数量更新时可以添加额外逻辑
}

function calculateTotal() {
    let total = 0
    for (let i = 0; i < orderVo.details.length; i++) {
        total += orderVo.details[i].buyCount * orderVo.details[i].salePrice
    }
    return total.toFixed(2)
}

function commit() {
    submitting.value = true
    const custmerId = store.userinfo.id;
    let cnt = 0
    for (let i = 0; i < orderVo.details.length; i++) {
        cnt += orderVo.details[i].buyCount * orderVo.details[i].salePrice
    }
    orderVo.order.custmerId = store.userinfo.id;
    orderVo.order.totalCount = cnt
    orderVo.order.targetAddr = address.value
    
    axios.post("/orderapi/orders", orderVo).then(res => {      
        ElMessage.success('订单提交成功')         
        axios.delete('/shopcartapi/customers/'+custmerId+'/shopcarts').then(() => {
            submitting.value = false
            router.push('/products')
        })
    }).catch(err => {
        ElMessage.error('订单提交失败')
        submitting.value = false
    }) 
} 

function goBack(){
    router.back();
}

onMounted(() => {
    findCarts(store.userinfo.id)
    
})
</script>

<style scoped>
.checkout-container {
    max-width: 1000px; /* 减小容器宽度 */
    padding: 15px; /* 减小内边距 */
}

.cart-item {
    padding: 10px; /* 减小商品项内边距 */
    margin-bottom: 10px; /* 减小商品项间距 */
}

.product-image {
    width: 60px; /* 减小商品图片宽度 */
    height: 60px; /* 减小商品图片高度 */
}

.product-name {
    font-size: 14px; /* 减小商品名称字体大小 */
}

.product-price {
    font-size: 14px; /* 减小价格字体大小 */
}

.remove-button {
    height: 30px; /* 减小删除按钮高度 */
    width: 30px; /* 减小删除按钮宽度 */
}

.item-total {
    font-size: 14px; /* 减小小计字体大小 */
}

.total-price {
    font-size: 16px; /* 减小总计字体大小 */
}

.total-amount {
    font-size: 20px; /* 减小总计金额字体大小 */
}

.submit-button, .back-button {
    padding: 8px 20px; /* 减小按钮内边距 */
    font-size: 14px; /* 减小按钮字体大小 */
}
</style>